﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private Thread th1 = null;//创建线程
        Socket socketSend = null;
        public Form1()
        {
            InitializeComponent();
            //关闭 跨线程检测
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                /*******服务端*******/

                //点击开始监听 在服务器端创建一个负责监IP地址跟端口号的Socket
                Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


                //创建IP端口和对象
                IPAddress ip = IPAddress.Parse(txt_IP.Text.Trim());
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txt_point.Text.Trim()));
                //监听
                socketWatch.Bind(point);
                txt_msg.AppendText("开始监听成功\r\n" + " [" + DateTime.Now.ToLongTimeString() + "] : ");

                //将监听套接字置于侦听状态，并设置连接队列的最大长度 
                socketWatch.Listen(10);

                //开始线程
                th1 = new Thread(Listen);
                th1.IsBackground = true; //线程设置副线程
                                         //线程开始等待
                th1.Start(socketWatch);//执行Listen方法 等待客户端的链接，并创建与之通讯用的Socket
            }
            catch (Exception err)
            {
                txt_receive.AppendText(" [" + DateTime.Now.ToLongTimeString() + "] : " + err + "/r/n");
               
            }

        }

        /// <summary>
        /// 等待客户端的链接，并创建与之通讯用的Socket
        /// </summary>
        /// <param name="o"></param>
        void Listen(object o)//使用线程 参数只能用object 对象
        {
            try
            {
                Socket socketWatch = o as Socket;

                //等待客户端连接 并创建一个负责通讯的Socket
                while (true)
                {

                    socketSend = socketWatch.Accept();
                    //连接成功
                    txt_msg.AppendText(" [" + DateTime.Now.ToLongTimeString() + "] : " + socketSend.RemoteEndPoint.ToString() + ":连接成功！\r\n");

                    //开启一个新的线程 不停的接受客户端发过来的消息
                    Thread th2 = new Thread(Recive);
                    th2.IsBackground = true;
                    th2.Start(socketSend);//执行Recive方法 服务器端不停的接受客户端发过来的消息

                }
            }
            catch (Exception e)
            {
                txt_receive.AppendText(" [" + DateTime.Now.ToLongTimeString() + "] : " + e + "\r\n");
          
            }
        }


        /// <summary>
        /// 服务器端不停的接受客户端发过来的消息
        /// </summary>
        /// <param name="o"></param>
        void Recive(object o)
        {
            try
            {
                while (true)
                {

                    Socket socketSend = o as Socket;
                    //客户端链接成功后，服务器应该接受客户端发来的消息
                    byte[] buffer = new byte[1024 * 1024 * 2];//字节数
                    int r = socketSend.Receive(buffer);//实际接受到的有效字节数量

                    if (r == 0)//判断如果是空消息就退出循环
                    {
                        txt_msg.AppendText(" [" + DateTime.Now.ToLongTimeString() + "] : " + socketSend.RemoteEndPoint.ToString() + " : 退出链接 \r\n");
                        break;
                    }
                    Console.WriteLine(111);
                    Console.WriteLine(buffer);
                    txt_receive.AppendText(buffer.ToString());
                    string str_msg = Encoding.UTF8.GetString(buffer, 0, r);//把接受到的字节转成字符串

                    //显示消息
                    txt_receive.AppendText(socketSend.RemoteEndPoint.ToString() + " [" + DateTime.Now.ToLongTimeString() + "] : " + str_msg + "\r\n");


                }
            }
            catch (Exception e)
            {
                txt_receive.AppendText(" [" + DateTime.Now.ToLongTimeString() + "] : " + e + "\r\n");
               
            }
        }

        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            string str_msg = txt_send.Text.Trim();//发送的消息
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str_msg);//转字节数

            socketSend.Send(buffer);//向服务器发送字节
            txt_receive.AppendText("我 [" + DateTime.Now.ToLongTimeString() + "] : " + str_msg + "\r\n");
            txt_send.Text = "";
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
